<template>
  <a-modal
    v-model:open="visible"
    title="编辑课件"
    centered
    :width="416"
    :maskClosable="false"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <div v-if="init" class="float-left text-center mt-30">
      <a-spin />
    </div>
    <div v-else class="float-left mt-24">
      <a-form
        :model="formState"
        :rules="rules"
        ref="formRef"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="课件分类" name="category_id">
          <a-tree-select
            v-model:value="formState.category_id"
            :tree-data="categories"
            tree-default-expand-all
            show-checked-strategy="SHOW_ALL"
            allow-clear
            style="width:200px"
            placeholder="课件分类"
          />
        </a-form-item>

        <a-form-item label="课件名称" name="name">
          <a-input
            v-model:value="formState.name"
            allow-clear
            style="width:200px"
            placeholder="请输入课件名称"
          />
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import { message } from "ant-design-vue";
import { resource, resourceCategory } from "@/api";

interface PropInterface {
  id: number;
  open: boolean;
  onCancel: () => void;
  onSuccess: () => void;
}

const props = defineProps<PropInterface>();
const emit = defineEmits(["update:open"]);

const visible = ref(false);
const init = ref(true);
const loading = ref(false);
const categories = ref<any[]>([]);
const formRef = ref();

const formState = ref({
  name: "",
  category_id: undefined as number | undefined,
});

const rules = {
  category_id: [{ required: true, message: "请选择课件分类!" }],
  name: [{ required: true, message: "请输入课件名称!" }],
};

// 监听 props.open
watch(
  () => props.open,
  (val) => {
    visible.value = val;
    if (val) {
      init.value = true;
      if (props.id !== 0) {
        getCategory();
        getDetail();
      }
    }
  }
);

const getCategory = async () => {
  const res = await resourceCategory.resourceCategoryList();
  const cats = res.data.categories;
  if (JSON.stringify(cats) !== "{}") {
    categories.value = checkArr(cats, 0, null);
  }
};

const getDetail = async () => {
  const res = await resource.videoDetail(props.id);
  const data = res.data.resources;
  formState.value.name = data.name;
  formState.value.category_id = res.data.category_ids;
  init.value = false;
};

const checkArr = (departments: any[], id: number, counts: any) => {
  const arr: any[] = [];
  for (let i = 0; i < departments[id].length; i++) {
    if (!departments[departments[id][i].id]) {
      arr.push({
        title: departments[id][i].name,
        value: departments[id][i].id,
      });
    } else {
      const newArr: any = checkArr(departments, departments[id][i].id, counts);
      arr.push({
        title: departments[id][i].name,
        value: departments[id][i].id,
        children: newArr,
      });
    }
  }
  return arr;
};

const handleOk = () => {
  formRef.value.validate().then(() => {
    submitForm();
  });
};

const handleCancel = () => {
  emit("update:open", false);
  props.onCancel();
};

const submitForm = async () => {
  loading.value = true;
  let values = { ...formState.value };
  if (Array.isArray(values.category_id)) {
    values.category_id = values.category_id[0];
  }
  try {
    await resource.videoUpdate(props.id, values);
    message.success("保存成功！");
    emit("update:open", false);
    props.onSuccess();
  } catch (e) {
  } finally {
    loading.value = false;
  }
};
</script>
